package cn.tannn.ip2region.server.api;

import cn.tannn.ip2region.sdk.config.SearcherConfig;
import cn.tannn.jdevelops.result.response.ResultVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;

/**
 * 数据管理
 *
 * @author <a href="https://tannn.cn/">tan</a>
 * @date 2024/4/3 14:57
 */
@Tag(name = "ip2regionxdb数据处理", description = "ip2regionxdb数据处理")
@RestController
@RequestMapping("data")
@Slf4j
public class DataController {

    /**
     * 重新加载ip2region.xdb ， 更换资源目录下的 ip2region.xdb 后热生效
     */
    @Operation(summary = "重新加载ip2region.xdb")
    @GetMapping("use")
    public ResultVO<String> use(){
        try {
            log.info("重新加载ip2region.xdb");
            InputStream inputStream = new ClassPathResource("/ipdb/ip2region.xdb").getInputStream();
            byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
            SearcherConfig.searcher = Searcher.newWithBuffer(bytes);
        } catch (Exception exception) {
            log.error("加载ip2region文件失败", exception);
        }
        return ResultVO.success();
    }

}
